import { login, logout, getInfo } from '@/api/userManage'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  realname: '',
  avatar: '',
  roles: '',
  menuAuth: '', // 菜单权限
  pageAuth: '', // 页面权限
  menus: [] // 拥有的菜单
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_REALNAME: (state, realname) => {
    state.realname = realname
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENUAUTH: (state, menuAuth) => {
    state.menuAuth = menuAuth
  },
  SET_PAGEAUTH: (state, pageAuth) => {
    state.pageAuth = pageAuth
  },
  SET_MENUS: (state, userMenus) => {
    state.menus = userMenus
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, userPassword } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), userPassword: userPassword }).then(response => {
        const data = response
        if (data.error) {
          reject(data.error)
        } else {
          commit('SET_TOKEN', data.token) // settoken
          setToken(data.token) // set cookie

          if (response.menus) {
            commit('SET_MENUS', response.menus)
          }

          resolve()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const data = response
        // console.info('-=-=-=-=-=-=-=-=-')
        // console.info(data.menus)
        if (!data) {
          reject('登录验证失败，请重新登录。')
        }

        const { userName, userRealname, userRoles, userMenuCodes, userPageAuths,menus } = data

        commit('SET_NAME', userName)
        commit('SET_REALNAME', userRealname)
        commit('SET_AVATAR', '@/assets/avatar/tavatar.gif')
        commit('SET_ROLES', userRoles)
        commit('SET_MENUAUTH', userMenuCodes)
        commit('SET_PAGEAUTH', userPageAuths)

        commit('SET_MENUS',menus)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

